package com.dreamder.service;

import java.text.SimpleDateFormat;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.StatusLine;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import org.json.JSONStringer;

import com.dreamder.model.UsuarioBeanTO;
import com.dreamder.util.DreamderConstants;

public class UsuarioService {

	public Boolean salvarUsuario(UsuarioBeanTO usuario) {

		try {

			HttpClient client = new DefaultHttpClient();

			HttpPost post = new HttpPost(DreamderConstants.URL_USUARIO
					+ "cadastrar");

			post.setHeader("Content-type", "application/json");

			JSONStringer json = new JSONStringer();
			json.object();
			json.key("nome").value(usuario.getNome());
			json.key("email").value(usuario.getEmail());

			SimpleDateFormat sdf = new SimpleDateFormat("dd-MM-yyyy");

			json.key("dataNascimento").value(
					sdf.format(usuario.getDataNascimento().getTime()));
			json.key("sexo").value(usuario.getSexo());
			json.key("fotoPerfil").value(usuario.getFotoPerfil());
			json.key("login").value(usuario.getLogin());
			json.key("senha").value(usuario.getSenha());
			json.endObject();

			HttpEntity entity = new StringEntity(json.toString());

			post.setEntity(entity);

			HttpResponse response = client.execute(post);

			String resposta = EntityUtils.toString(response.getEntity());

			if (resposta.equals("usuario criado")) {
				return true;
			} else {
				return false;
			}

		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return false;
		}
	}

	public String logarUsuario(UsuarioBeanTO usuario) {

		try {

			HttpClient client = new DefaultHttpClient();

			HttpPost post = new HttpPost(DreamderConstants.URL_USUARIO
					+ "logar");

			post.setHeader("Content-type", "application/json");

			JSONStringer json = new JSONStringer();
			json.object();
			json.key("login").value(usuario.getLogin());
			json.key("senha").value(usuario.getSenha());
			json.endObject();

			HttpEntity entity = new StringEntity(json.toString());

			post.setEntity(entity);

			HttpResponse response = client.execute(post);
			
			StatusLine status = response.getStatusLine();
			
			if(status.getStatusCode() == 200){
				HttpEntity resposta = response.getEntity();
				String respostaEmJSON = EntityUtils.toString(resposta);
				return respostaEmJSON;
			}
			
			return "ERRO";

		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return "ERRO";
		}

	}
}
